# 1.定义 序列化器 --- 序列化 反序列化
from rest_framework import serializers

from books.models import BookInfo, HeroInfo


class HeroInfoModelSerializer(serializers.ModelSerializer):


    class Meta:
        # 1. 序列化 哪个模型类
        model = HeroInfo
        # 2. 模型类中的 哪些字段
        fields = "__all__"
        # fields = ['id', 'hname']


# 定义校验 方法
def about_drf(value):
    if 'drf' not in value:
        raise serializers.ValidationError('必须有 drf 的书名')
    return value


class BookInfoMySerializer(serializers.Serializer):
    # 对应 模型类的字段 -----> 类型
    id = serializers.IntegerField(read_only=True, help_text="主键ID")
    btitle = serializers.CharField(
        max_length=20,
        min_length=5,
        error_messages={
            'required': "书名不能为空",
            'min_length': "书名不能小于5",
            'max_length': "书名不能大于20",

        },
        validators=[about_drf]
    )
    bpub_date = serializers.DateField()

    bread = serializers.IntegerField(required=False)
    bcomment = serializers.IntegerField(required=False)
    is_delete = serializers.BooleanField(required=False)

    # 看到 英雄的信息 1:n 隐藏属性1.n_set
    heroinfo_set = serializers.StringRelatedField(many=True, read_only=True)

    # 1.自定义校验  1个字段 btitle
    # def validate_btitle(self, value):
    #     if 'drf' not in value:
    #         raise serializers.ValidationError('书名必须有:Drf')
    #     return value
    #
    # #2. 校验  多个字段
    # def validate(self, attrs):
    #     bread = attrs['bread']
    #     bcomment = attrs['bcomment']
    #
    #     if bread <  bcomment:
    #         raise serializers.ValidationError('阅读量  必须 大于  评论量')
    #     return attrs

    # 插入数据库数据  必须重写父类的create方法
    def create(self, validated_data):
        # 插入数据库
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """

        :param instance:  修改的对象
        :param validated_data:  修改的数据(校验通过了)
        :return:
        """

        instance.btitle = validated_data.get('btitle')
        instance.bpub_date = validated_data.get('bpub_date')
        instance.bread = validated_data.get('bread')
        instance.bcomment = validated_data.get('bcomment')
        instance.is_deleted = validated_data.get('is_deleted')
        instance.save()

        return instance


class HeroInfoMySerializer(serializers.Serializer):
    GENDER_CHOICES = (
        (0, 'female'),
        (1, 'male')
    )
    hname = serializers.CharField(max_length=30)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, default=0)

    # n:1  看 英雄属于 的书籍---外键属性
    # hbook = serializers.PrimaryKeyRelatedField(read_only=True)
    # hbook = serializers.StringRelatedField(read_only=True)
    hbook = BookInfoMySerializer()




class BookInfoSerializer(serializers.ModelSerializer):
    """图书数据序列化器"""
    heroinfo_set = serializers.StringRelatedField(read_only=True, many=True)
    class Meta:
        model = BookInfo  # 告诉他  序列化/反序列化 哪个模型类
        fields = "__all__"  # 告诉他  序列化/反序列化 哪些字段

    # drf 中 类视图 和 请求对象 -- 会在 序列化器对象实例化的时候  通过 context 额外参数 传递到对象里面 方便后期开发
    # def create(self, validated_data):
    #     print(self.context['view'].queryset)
    #
    #     return 'hahah'

